/*
 * Copyright (C) 2013 tangzhi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.tangzsoft.pdmviewer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.tangzsoft.pdmviewer.model.PdmObject;
import org.tangzsoft.pdmviewer.utils.Utils;

/**
 * 主窗口右侧多tab页中的某一个分页。
 * 该分页包含上下两个部分：
 *  1、上面为过滤部分。过滤部分，包含过滤选项，和过滤关键字。
 *  2、下面为主体工作部分。内容部分又分为上下两个部分：
 *      a、上面为对象列表部分。该部分内容可以通过关键字进行过滤
 *      b、下面部分为某一对象的详细内容
 * @author tangzhi
 */
public class PdmObjectView extends JPanel {
    
    private final static String[] COLUMN_NAME = { "Code", "Name", "ObjectType", "Comment"}; 
    private final static int[] COLUMN_WIDTH = {50, 80, 30, 100};
    
    private JSplitPane spWorkArea;
    
    private JTable poTable;
    
    JTextField tfFilter;
    
    /**
     * 对象列表的TableModel
     */
    class PdmObjectTableModel extends AbstractTableModel {
        
        private PdmObject[] objs;
        
        PdmObjectTableModel(PdmObject[] objs) {
            this.objs = objs;
        }
        
        @Override
        public int getRowCount() {
            return objs.length;
        }

        @Override
        public int getColumnCount() {
            return COLUMN_NAME.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return Utils.getValue(objs[rowIndex], COLUMN_NAME[columnIndex]);
        }
        
        @Override
        public String getColumnName(int column) {
            return COLUMN_NAME[column];
        }
    }
    
    /**
     * 创建过滤部件
     * 过滤部件总体采用BoxLayout布局.
     * @return 
     */
    private JPanel createFilterArea() {
        JPanel pnlFilter = new JPanel();
        
        pnlFilter.setLayout(new BoxLayout(pnlFilter, BoxLayout.X_AXIS));
        
        JLabel scope = new JLabel("scope:");
        
        //设置左边距5，右边距3
        scope.setBorder(BorderFactory.createEmptyBorder(0,5,0,3));
        
        JCheckBox table = new JCheckBox("Table");
        table.setSelected(true);
        
        JCheckBox column = new JCheckBox("Column");
        
        JCheckBox sequence = new JCheckBox("Sequence");
        
        //
        pnlFilter.add(scope);
        pnlFilter.add(table);
        pnlFilter.add(Box.createHorizontalStrut(2));
        pnlFilter.add(column);
        pnlFilter.add(Box.createHorizontalStrut(2));
        pnlFilter.add(sequence);
        
        //
        
        pnlFilter.add(Box.createHorizontalGlue());
        
        //
        JLabel msg = new JLabel();
        msg.setBorder(BorderFactory.createEmptyBorder(0, 3, 0, 2));
        Dimension min = new Dimension(50, 28);
        msg.setMaximumSize(min);
        msg.setMinimumSize(min);
        msg.setBackground(Color.red);
        pnlFilter.add(msg);
        
        //
        tfFilter = new JTextField("Filter Objects...");
        min = new Dimension(140, 28);
        tfFilter.setMinimumSize(min);
        tfFilter.setMaximumSize(min);
        tfFilter.setPreferredSize(min);
        
        tfFilter.addFocusListener(new FocusListener(){

            @Override
            public void focusGained(FocusEvent e) {
                tfFilter.selectAll();
            }

            @Override
            public void focusLost(FocusEvent e) {
            }
            
        });
        
        pnlFilter.add(tfFilter);
        pnlFilter.add(Box.createHorizontalStrut(5));
        
        return pnlFilter;
    }
    
    
    /**
     * 创建主体工作部分
     * @return 
     */
    private JSplitPane createWorkArea() {
        spWorkArea = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        
        poTable = new JTable();
        poTable.setAutoCreateRowSorter(true);
        
        spWorkArea.setTopComponent(new JScrollPane(poTable));
        
        spWorkArea.setBottomComponent(new JTabbedPane());
        
        spWorkArea.setDividerLocation(200);
        
        return spWorkArea;
    }
    
    public PdmObjectView(PdmObject[] objects) {
        super(new BorderLayout());
        
        add(createFilterArea(), BorderLayout.NORTH);
        
        add(createWorkArea(), BorderLayout.CENTER);
        
        showPdmObjects(objects);
    }
    
    /**
     * 设置数据，并且按名称排序
     * @param objects 
     */
    public final void showPdmObjects(PdmObject[] objects) {
        poTable.setModel(new PdmObjectTableModel(objects));
        
        //按表名进行排序
        final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(poTable.getModel());
        poTable.setRowSorter(sorter);
        
        List <RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
        sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
        sorter.setSortKeys(sortKeys); 
        sorter.setRowFilter(null);
        
        
        //设置过滤
        tfFilter.getDocument().addDocumentListener(
                new DocumentListener() {
                    
                    private void newFilter() {
                        RowFilter<TableModel, Object> rf = null;
                        //If current expression doesn't parse, don't update.
                        try {
                            rf = RowFilter.regexFilter(tfFilter.getText(), 0);
                        } catch (java.util.regex.PatternSyntaxException e) {
                            return;
                        }
                        
                        sorter.setRowFilter(rf);
                    }
                    
                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        newFilter();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        newFilter();
                    }

                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        newFilter();
                    }
        
                }
        );
    }
    
    /**
     * 初始化表格列宽
     */
    private void initColWidth() {
        for (int i=0,j=COLUMN_WIDTH.length; i<j; ++i) {
            poTable.getColumnModel().getColumn(i).setPreferredWidth(COLUMN_WIDTH[i]);
        }
    }
}
